package com.mf.morefun.widget;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Environment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mf.morefun.MoreFunApplication;
import com.mf.morefun.R;
import com.mf.morefun.bean.LocalListenBean;
import com.mf.morefun.constant.Configuration;
import com.mf.morefun.ui.person.MineInfoActivity;
import com.mf.morefun.ui.userinfo.LoginActivity;
import com.zhcx.zhcxlibrary.utils.AppManager;
import com.zhcx.zhcxlibrary.utils.SPUtils;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.xutils.DbManager;
import org.xutils.x;

import java.io.File;
import java.util.List;

public class BackIdeaPop {
    private Context mContext;
    private SPUtils mSputils;
    private DbManager mDbManager;
    public BackIdeaPop(Context mContext) {
        this.mContext = mContext;
        mSputils = new SPUtils(mContext);
        mDbManager = x.getDb(MoreFunApplication.daoConfig);
    }
    public void showPop(String text, int type, int position){
        try {
            if (null != MoreFunApplication.mIdeaPop && MoreFunApplication.mIdeaPop.isShowing()){
                MoreFunApplication.mIdeaPop.dismiss();
                MoreFunApplication.mIdeaPop = null;
                showPop(text, type, position);
            }else {
                View view = LayoutInflater.from(mContext).inflate(R.layout.layout_popidea, null);
                RelativeLayout rl_bg = view.findViewById(R.id.rl_bg);
                rl_bg.getBackground().setAlpha(100);
                TextView tv_info = view.findViewById(R.id.tv_idea);
                if (!StringUtils.isEmpty(text)){
                    tv_info.setText(text);
                }
                TextView tv_close = view.findViewById(R.id.tv_cancel);
                tv_close.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MoreFunApplication.mIdeaPop.dismiss();
                        MoreFunApplication.mIdeaPop = null;
                    }
                });
                TextView tv_sure = view.findViewById(R.id.tv_sure);
                tv_sure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MoreFunApplication.mIdeaPop.dismiss();
                        MoreFunApplication.mIdeaPop = null;
                        try {
                            if (type == 0){
                                mSputils.putString(Configuration.USERID, "");
                                mSputils.putString(Configuration.USERPASSWORD, "");
                                mSputils.remove(Configuration.USERID);
                                mSputils.remove(Configuration.USERPASSWORD);
                                AppManager.getAppManager().finishAllActivity();
                                Intent mIntent = new Intent(mContext, LoginActivity.class);
                                mContext.startActivity(mIntent);
                                AppManager.getAppManager().finishActivity(mContext.getClass());
                            }else if(type == 1){
                                try {
                                    delete(getBasePath());
                                    delete(Environment.getExternalStorageDirectory() + "/listenMusic");
                                    List<LocalListenBean> list = mDbManager.findAll(LocalListenBean.class);
                                    if (null != list && list.size() > 0) {
                                        for (int i = 0; i < list.size(); i++) {
                                            mDbManager.delete(list.get(i));
                                        }
                                    }
                                    ToastUtils.show(mContext, "清除缓存成功", 100);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    ToastUtils.show(mContext, "清除缓存失败", 100);
                                }
                            }else if(type == 2){
                                Intent mIntent = new Intent();
                                mIntent.putExtra("POSITION", position);
                                mIntent.setAction("DELETE");
                                mContext.sendBroadcast(mIntent);
                            }else if(type == 3){
                                AppManager.getAppManager().finishActivity(mContext.getClass());
                            }else if(type == 4){
                                AppManager.getAppManager().finishActivity(mContext.getClass());
                            }else if(type == 5){
                                Intent mIntent = new Intent();
                                mIntent.putExtra("POSITION", position);
                                mIntent.setAction("DELETEPERSON");
                                mContext.sendBroadcast(mIntent);
                            }else if(type == 6){
                                Intent mIntent = new Intent();
                                mIntent.putExtra("POSITION", position);
                                mIntent.setAction("DELETECLASS");
                                mContext.sendBroadcast(mIntent);
                            }else if(type == 7){//提交录音
                                Intent mIntent = new Intent();
                                mIntent.setAction("POSTRECORD");
                                mContext.sendBroadcast(mIntent);
                            }else if(type == 8){//提交视频
                                Intent mIntent = new Intent();
                                mIntent.setAction("POSTVIDEO");
                                mContext.sendBroadcast(mIntent);
                            }else if(type == 9){
                                Intent mIntent = new Intent();
                                mIntent.putExtra("POSITION", position);
                                mIntent.setAction("DELETECLASSSIMPLEHOMEWORK");
                                mContext.sendBroadcast(mIntent);
                            }else if(type == 10){
                                Intent mIntent = new Intent();
                                mIntent.putExtra("POSITION", position);
                                mIntent.setAction("DELETECLASSHOMEWORK");
                                mContext.sendBroadcast(mIntent);
                            }else if(type == 11){
                                Intent mIntent = new Intent();
                                mIntent.putExtra("POSITION", position);
                                mIntent.setAction("CHANGEPASSWORD");
                                mContext.sendBroadcast(mIntent);
                            }else if(type == 12){
                                Intent mIntent = new Intent();
                                mIntent.setAction("SUBMITHOMEWORK");
                                mContext.sendBroadcast(mIntent);
                            }else if(type == 13){
                                AppManager.getAppManager().finishActivity(mContext.getClass());
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                });
                MoreFunApplication.mIdeaPop = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
                MoreFunApplication.mIdeaPop.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                MoreFunApplication.mIdeaPop.setBackgroundDrawable(new BitmapDrawable());
                MoreFunApplication.mIdeaPop.setFocusable(true);
                MoreFunApplication.mIdeaPop.update();
                MoreFunApplication.mIdeaPop.showAtLocation(view, Gravity.CENTER, 0, 0);
                MoreFunApplication.mIdeaPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        MoreFunApplication.mIdeaPop.dismiss();
                        MoreFunApplication.mIdeaPop = null;
                    }
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public String getBasePath() {
        String strPath = null;
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            strPath = mContext.getFilesDir() + "/" + "lameMp3";
        } else {
            strPath = Environment.getExternalStorageDirectory() + "/" + "lameMp3";
        }
        File dir = new File(strPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return strPath;
    }

    /**
     * 删除文件，可以是文件或文件夹
     *
     * @param fileName 要删除的文件名
     * @return 删除成功返回true，否则返回false
     */
    public boolean delete(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            System.out.println("删除文件失败:" + fileName + "不存在！");
            return false;
        } else {
            if (file.isFile())
                return deleteFile(fileName);
            else
                return deleteDirectory(fileName);
        }
    }

    /**
     * 删除目录及目录下的文件
     *
     * @param dir 要删除的目录的文件路径
     * @return 目录删除成功返回true，否则返回false
     */
    public boolean deleteDirectory(String dir) {
        // 如果dir不以文件分隔符结尾，自动添加文件分隔符
        if (!dir.endsWith(File.separator))
            dir = dir + File.separator;
        File dirFile = new File(dir);
        // 如果dir对应的文件不存在，或者不是一个目录，则退出
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            System.out.println("删除目录失败：" + dir + "不存在！");
            return false;
        }
        boolean flag = true;
        // 删除文件夹中的所有文件包括子目录
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
            // 删除子目录
            else if (files[i].isDirectory()) {
                flag = deleteDirectory(files[i]
                        .getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag) {
            System.out.println("删除目录失败！");
            return false;
        }
        // 删除当前目录
        if (dirFile.delete()) {
            System.out.println("删除目录" + dir + "成功！");
            return true;
        } else {
            return false;
        }
    }

    /**
     * 删除单个文件
     *
     * @param fileName 要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("删除单个文件" + fileName + "成功！");
                return true;
            } else {
                System.out.println("删除单个文件" + fileName + "失败！");
                return false;
            }
        } else {
            System.out.println("删除单个文件失败：" + fileName + "不存在！");
            return false;
        }
    }


}
